package han.Chensing.CCirnosLibrary.util;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class MD5Util {
    public static String getMD5OfFile(File file){
        try {
            FileInputStream inputStream=new FileInputStream(file);
            byte[] bytes=new byte[2048];
            int read;
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            while((read=inputStream.read())!=-1)
                messageDigest.update(bytes,0,read);
            inputStream.close();
            byte[] digest = messageDigest.digest();
            return StringUtil.byteToHdxString(digest);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String getMD5OfString(String s){
        try{
            MessageDigest messageDigest=MessageDigest.getInstance("MD5");
            byte[] digest = messageDigest.digest(s.getBytes(StandardCharsets.UTF_8));
            return StringUtil.byteToHdxString(digest);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
